package com.weipai.springboot.module.service.impl;

import com.weipai.springboot.enums.ClientType;
import com.weipai.springboot.enums.GoodsStatus;
import com.weipai.springboot.enums.RetCode;
import com.weipai.springboot.model.*;
import com.weipai.springboot.model.api.GoodsItem;
import com.weipai.springboot.model.api.GoodsItemResult;
import com.weipai.springboot.model.api.PageResult;
import com.weipai.springboot.model.api.Response;
import com.weipai.springboot.module.dao.*;

import com.weipai.springboot.module.mapper.*;
import com.weipai.springboot.module.service.GoodsService;
import com.weipai.springboot.module.util.DateUtils;
import net.sf.json.JSONArray;
import net.sf.json.JsonConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * @Author: 曹朋飞
 * @Date: 2018/08/22 15:22
 */
@Service
public class GoodsServiceImpl implements GoodsService {

    private static final Logger logger = LoggerFactory.getLogger(GoodsServiceImpl.class);

    @Autowired
    ProductDao productDao;
    @Autowired
    GoodsDao goodsDao;
    @Autowired
    PropertyOptionDao propertyOptionDao;
    @Autowired
    GoodsPriceDao goodsPriceDao;
    @Autowired
    GoodsOptionDao goodsOptionDao;
    @Autowired
    EvaluateDao evaluateDao;
    @Autowired
    ProductPropertyDao productPropertyDao;
    @Autowired
    SolrDao solrDao;
    @Autowired
    BrandMapper brandMapper;
    @Autowired
    GoodsCollectionDao goodsCollectionDao;
    @Autowired
    ProductCategoryDao productCategoryDao;
    @Autowired
    private CustomerDao customerDao;
    @Autowired
    ProductMapper productMapper;
    @Autowired
    GoodsMapper goodsMapper;
    @Autowired
    IntegralGoodsMapper integralGoodsMapper;
    @Autowired
    SolrTestMapper solrTestMapper;

    //保存
    @Override
    @Transactional(readOnly=false, propagation = Propagation.REQUIRED)
    public Response save(Product product, ProductDesc productDesc, String goodsInfo, String productPro) {
        Response response = new Response();
        //商品、商品与属性关联表配置
        List<GoodsOption> optionList = new ArrayList<>();
        List<Goods> goodsList = new ArrayList<>();
        List<GoodsPrice> goodsPrices = new ArrayList<>();
        JSONArray jsonArray = JSONArray.fromObject(goodsInfo);//把String转换为json
        List<GoodsInfo> goodsInfoList = JSONArray.toList(jsonArray, new GoodsInfo(), new JsonConfig());
        Integer newSpuNumber = serialNumber("P", null)+1;
        //Integer newSkuNumber = serialNumber("G");
        //Integer newSpuNumber = serialNumber("P")+1;
        product.setShopId("2249166d-40f0-4470-a294-fa236d4d103f");
        ProductCategory category = productCategoryDao.getProductCategoryById(product.getProductCategoryId());
        String spu;
        if(category.getInitial()!=null && category.getInitial()!=""){
            spu = category.getInitial()+newSpuNumber.toString();
        }else{
            spu = newSpuNumber.toString();
        }
        product.setSpuNumber(spu);
        product.setSpuNumberFlag(newSpuNumber);
        int size01 = goodsInfoList.size();
        for (int f = 0; f < size01; f++) {
            Goods goods = new Goods();
            goods.setSkuNumberFlag(f+1);
            goods.setGoodsSpec(goodsInfoList.get(f).getSpec()[goodsInfoList.get(f).getSpec().length - 1]);
            goods.setGoodsName(product.getProductName() + "(" + goodsInfoList.get(f).getSpec()[1].toString() + ")");
            goods.setSpuNumber(product.getSpuNumber());
            goods.setSkuNumber(spu+"-"+(f+1));
            //newSkuNumber = newSkuNumber+1;
            //goods.setSkuNumber(newSkuNumber.toString());

            goods.setShopId(product.getShopId());
            goods.setWaringValue(goodsInfoList.get(f).getWaringValue());
            goods.setCostPrice(goodsInfoList.get(f).getCostPrice());
            goods.setOriginalPrice(goodsInfoList.get(f).getOriginalPrice());
            goods.setCurrentPrice(goodsInfoList.get(f).getCurrentPrice());

            String[] price =goodsInfoList.get(f).getSellingPrice();
            int size03 = price.length;
            for(int y=0;y<size03;y++){
                addGoodsPrice(price[y], goods.getGoodsId(), goodsPrices);
            }
            String optionId = goodsInfoList.get(f).getSpec()[0];
            String[] newData = optionId.split(",");
            int size02 = newData.length;
            for (int t = 0; t < size02; t++) {
                addGoodsOption(goods.getGoodsId(),newData[t], optionList);
            }
            goodsList.add(goods);
        }
        productDesc.setProductId(product.getProductId());
        productDesc.setSpuNumber(product.getSpuNumber());

        List<ProductPro> proList = new ArrayList<>();
        String[] pros = productPro.split(",");
        int size02 = pros.length;
        for(int i=0;i<size02;i++){
            ProductPro productPro1 = new ProductPro();
            productPro1.setProductId(product.getProductId());
            productPro1.setPropertyId(pros[i]);
            proList.add(productPro1);
        }
        productDao.saveProductPro(proList);
        //保存
        productDao.saveProductDesc(productDesc);    //产品的详情和主图表  c_product_desc
        productDao.save(product);                   //产品 (货品) - product
        goodsDao.save(goodsList);                           //商品 - goods
        goodsOptionDao.save(optionList);                    //商品与属性选项值关系表   c_goods_option
        goodsPriceDao.save(goodsPrices);
        response.setCode(RetCode.SUCCESS);
        return response;
    }

    //删除商品
    @Override
    public Response deleteByGoodsById(String id) {
        Response response = new Response();
        int i = goodsDao.deleteByGoodsById(id);

        if (1 == i) {

            deleteGoodsIndex(id);   //如直接删除商品 则 也直接从索引库删除

            //查询是否是积分商品, 是则一起  逻辑删除
            IntegralGoods integralGoods = integralGoodsMapper.selectByGoodsId(id);
            if(integralGoods!=null){
                integralGoods.setIntegralGoodsDel(-1);
             int j = integralGoodsMapper.updateByPrimaryKeySelective(integralGoods);
            }
            response.setCode(RetCode.SUCCESS);
        } else {
            response.setCode(RetCode.REQUEST_ERROR);
        }
        return response;
    }


    //删除产品
    @Override
    public Response deleteProductBySpuNumber(String spuNumber) {
        Response response = new Response();
        List<Map<String, Object>> map = goodsDao.getGoodsIdByProductId(spuNumber);
        int size01 = map.size();
        for(int i=0;i<size01;i++){
            deleteGoodsIndex(map.get(i).get("goodsId").toString());//如直接删除商品 则 也直接从索引库删除
            goodsDao.deleteByGoodsById(map.get(i).get("goodsId").toString());
        }
        productDao.deleteProductBySpuNumber(spuNumber);
        response.setCode(RetCode.SUCCESS);
        return response;
    }


    //通过商品的id获取商品详情
    @Override
    public Response getGoodsInfoByGoodsId(String goodsId) {
        Response response = new Response();
        Goods goods = goodsDao.selectByPrimaryKey(goodsId);
        if(null != goods){
            GoodsInfo goodsInfo = new GoodsInfo();
            goodsInfo.setSpec(new String[]{goods.getGoodsSpec()});
            goodsInfo.setCostPrice(goods.getCostPrice());
            goodsInfo.setOriginalPrice(goods.getOriginalPrice());
            goodsInfo.setCurrentPrice(goods.getCurrentPrice());
            goodsInfo.setWaringValue(goods.getWaringValue());
            List<String> list03 = new ArrayList<>();
            //查出商品的各种级别对应的价格
            List<GoodsPrice> priceList = goodsPriceDao.getListByGoodsId(goodsId);
            int size04 = priceList.size();
            for (int e = 0; e < size04; e++) {
                list03.add(priceList.get(e).getGoodsPrice().toString());
            }
            goodsInfo.setSellingPrice(list03.toArray(new String[list03.size()]));
            response.setCode(RetCode.SUCCESS);
            response.put("data",goodsInfo);
        }else{
            response.setCode(RetCode.NO_DATA);
        }
        return response;
    }

    //检索商品
    @Override
    public Response searchGoods(String search, Integer page, Integer size) {
        Integer start = (page-1) * size;
        List<Map<String, Object>> goods = goodsDao.searchGoods(start, size, search);
        Integer totalNum = goodsDao.searchGoodsAmount(search);
        PageResult<Map<String, Object>> pageList = new PageResult<>(goods,page,size,totalNum, null);
        Response response = new Response();
        response.setCode(RetCode.SUCCESS);
        response.put("pageList", pageList);
        return response;
    }

    //秒杀商品和会场商品--前端商品详情
    @Override
    public Response getSpecialGoodsInfo(String id) {
        Response response = new Response();
        Map<String, Object> specialGoodsMap = goodsDao.getSpecialGoodsInfo(id);
        return response;
    }




    //更改商品的状态    商品上架 / 下架
    @Override
    public Response changeGoodsStatus(String id, Integer status) {
        Response response = new Response();
        if (status == GoodsStatus.ON_SHELVE.getStatus()) {                  //上架 时 把商品添加 solr 索引库
            saveGoodsIndex(id);
        } else if (status == GoodsStatus.OFF_SHELVES.getStatus()) {           //下架 时 把商品删除 solr 索引库
            deleteGoodsIndex(id);
        }
        int i = goodsDao.changeGoodsStatus(id, status);
        if (1 == i) {
            response.setCode(RetCode.SUCCESS);
        } else {
            response.setCode(RetCode.REQUEST_ERROR);
        }
        return response;
    }

    //更改产品的状态
    @Override
    public Response changeProductStatus(String spuNumber, Integer status) {
        Response response = new Response();
        List<Map<String, Object>> map = goodsDao.getGoodsIdByProductId(spuNumber);
        int size01 = map.size();
        for(int i=0;i<size01;i++){
            if(status==1){                  //上架 时 把商品添加 solr 索引库
                saveGoodsIndex(map.get(i).get("goodsId").toString());
            }else if(status==-1){           //下架 时 把商品删除 solr 索引库
                deleteGoodsIndex(map.get(i).get("goodsId").toString());
            }
            goodsDao.changeGoodsStatus(map.get(i).get("goodsId").toString(), status);
        }
        productDao.updateStatus(spuNumber, status);
        response.setCode(RetCode.SUCCESS);
        return response;
    }



    //根据product的id查询详情
    @Override
    public Response getProductInfoById01(String id) {
        Response response = new Response();
        Map<String, Object> map = productDao.getProductInfoById01(id);
        if (map.size() > 0) {
            response.setCode(RetCode.SUCCESS);
            response.setData(map);
        } else {
            response.setCode(RetCode.NO_DATA);
        }
        return response;
    }



    //根据product的id查询详情
    @Override
    public Response getProductInfoById02(String id, String categoryId, String spuNumber) {
        Response response = new Response();
        List<Map<String, Object>> list01 = new ArrayList<>();
        //查询出此分类下的所有属性
        List<ProductProperty> properties = productPropertyDao.selectAllByProductCategoryId(0, 100, categoryId);
        int size01 = properties.size();
        for (int i = 0; i < size01; i++) {
            //查询出此属性的基本信息
            Map<String, Object> map01 = new HashMap<>();
            map01.put("propertieId", properties.get(i).getPropertyId());
            map01.put("propertieName", properties.get(i).getPropertyName());
            //查询出此属性下的所有属性选项
            List<PropertyOption> optionList = propertyOptionDao.getOptionByPropertyId(properties.get(i).getPropertyId());
            List<Map<String, Object>> list02 = new ArrayList<>();
            int size02 = optionList.size();
            for (int j = 0; j < size02; j++) {
                Map<String, Object> map02 = new HashMap<>();
                map02.put("optionId", optionList.get(i).getOptionId());
                map02.put("optionValue", optionList.get(i).getOptionValue());
                list02.add(map02);
            }
            list01.add(map01);
        }
        //通过货品编号查出所有的商品
        List<Goods> goodsList = goodsDao.selectGoodsBySpuNumber(spuNumber);
        List<GoodsInfo> goodsInfoList = new ArrayList<>();
        int size03 = goodsList.size();
        for (int t = 0; t < size03; t++) {
            GoodsInfo goodsInfo = new GoodsInfo();
            //goodsInfo.setSpec(goodsList.get(t).getGoodsSpec());
            goodsInfo.setCostPrice(goodsList.get(t).getCostPrice());
            goodsInfo.setOriginalPrice(goodsList.get(t).getOriginalPrice());
            goodsInfo.setCurrentPrice(goodsList.get(t).getCurrentPrice());
            List<Integer> list03 = new ArrayList<>();
            //查出商品的各种级别对应的价格
            List<GoodsPrice> priceList = goodsPriceDao.getListByGoodsId(goodsList.get(t).getGoodsId());
            int size04 = priceList.size();
            for (int e = 0; e < size04; e++) {
                list03.add(priceList.get(e).getGoodsPrice());
            }
            goodsInfo.setSellingPrice(list03.toArray(new String[list03.size()]));
            goodsInfoList.add(goodsInfo);
        }
        response.setCode(RetCode.SUCCESS);
        response.put("optionList", list01);
        response.put("goodsList", goodsInfoList);
        return response;
    }

    @Override
    public Response searchGoodsByCategoryId(String categoryId, int page, int size, String draw) {
        Integer start = (page - 1) * size;
        List<Map<String, Object>> list = goodsDao.searchGoodsByCategoryId(categoryId, start, size);
        Integer totalNum = goodsDao.countGoodsByCategoryId(categoryId);
        PageResult<Map<String, Object>> pageList = new PageResult<>(list, page, size, 0, draw);
        Response response = new Response();
        response.setCode(RetCode.SUCCESS);
        response.put("pageList", pageList);
        return response;
    }

    @Override
    public Goods selectByGoodsId(String goodsId) {
        return goodsDao.selectByPrimaryKey(goodsId);
    }

    //更新货品
    @Override
    @Transactional(readOnly=false, propagation = Propagation.REQUIRED)
    public Response updateProduct(String productId, String productSpec, String productName, ProductDesc productDesc,
                                  Integer consumeIntegral, Integer commentIntegral,
                                  Integer isBoutique, Integer isNews, Integer isPackage) {
        Response response = new Response();
        Product product = productDao.selectByPrimaryKey(productId);
        product.setProductName(productName);
        product.setProductSpec(productSpec);
        product.setConsumeIntegral(consumeIntegral);
        product.setCommentIntegral(commentIntegral);
        product.setIsBoutique(isBoutique);
        product.setIsNews(isNews);
        product.setIsPackage(isPackage);
            List<Map<String, Object>> goodsList  = goodsDao.getGoodsInfoBySkuNumber(product.getSpuNumber());
            if(goodsList.size()>0){
                for (int i = 0; i < goodsList.size(); i++) {
                    Goods goods =goodsDao.selectByPrimaryKey(goodsList.get(i).get("goodsId").toString());
                    goods.setGoodsName(productName+"("+goods.getGoodsSpec()+")");
                    goodsDao.updateGoods(goods);
                }
            }
        int i = productDao.updateByPrimaryKeySelective(product);
        int j = productDao.updateProductDesc(productDesc);
        if (i == 1 && j == 1) {
            //更新索引库
                if(goodsList.size()>0){
                    for (int g = 0; g < goodsList.size(); g++) {
                        deleteGoodsIndex(goodsList.get(g).get("goodsId").toString());
                        saveGoodsIndex(goodsList.get(g).get("goodsId").toString());
                    }
                }
            response.setCode(RetCode.SUCCESS);
        } else {
            response.setCode(RetCode.REQUEST_ERROR);
        }
        return response;
    }

    //新增商品
    @Override
    @Transactional(readOnly=false, propagation = Propagation.REQUIRED)
    public Response saveGoods(String spuNumber, String goodsInfo) {
        Response response = new Response();
        //商品、商品与属性关联表配置
        List<GoodsOption> optionList = new ArrayList<>();
        List<Goods> goodsList = new ArrayList<>();
        List<GoodsPrice> goodsPrices = new ArrayList<>();
        JSONArray jsonArray = JSONArray.fromObject(goodsInfo);//把String转换为json
        List<GoodsInfo> goodsInfoList = JSONArray.toList(jsonArray, new GoodsInfo(), new JsonConfig());
        Integer skuNumberFlag = serialNumber("G", spuNumber);
        //Integer newSkuNumber = serialNumber("G");
        //通过spuNumber查询货品
        Map<String, String> product = productDao.getProductBySpuNumber(spuNumber);
        int size01 = goodsInfoList.size();
        for (int f = 0; f < size01; f++) {
            Goods goods = new Goods();
            goods.setSkuNumberFlag(skuNumberFlag+f+1);
            goods.setGoodsSpec(goodsInfoList.get(f).getSpec()[goodsInfoList.get(f).getSpec().length - 1]);
            goods.setGoodsName(product.get("productName") + "(" + goodsInfoList.get(f).getSpec()[1].toString() + ")");
            goods.setSpuNumber(spuNumber);
            goods.setSkuNumber(spuNumber+"-"+(skuNumberFlag+f+1));
            //newSkuNumber = newSkuNumber+1;
            //goods.setSkuNumber(newSkuNumber.toString());

            goods.setWaringValue(goodsInfoList.get(f).getWaringValue());
            goods.setCostPrice(goodsInfoList.get(f).getCostPrice());
            goods.setOriginalPrice(goodsInfoList.get(f).getOriginalPrice());
            goods.setCurrentPrice(goodsInfoList.get(f).getCurrentPrice());
            String[] price =goodsInfoList.get(f).getSellingPrice();
            int size03 = price.length;
            for(int y=0;y<size03;y++){
                addGoodsPrice(price[y], goods.getGoodsId(), goodsPrices);
            }
            String optionId = goodsInfoList.get(f).getSpec()[0];
            String[] newData = optionId.split(",");
            int size02 = newData.length;
            for (int i = 0; i < size02; i++) {
                addGoodsOption(goods.getGoodsId(),newData[i], optionList);
            }
            goodsList.add(goods);
        }
        goodsDao.save(goodsList);
        goodsOptionDao.save(optionList);
        goodsPriceDao.save(goodsPrices);
        response.setCode(RetCode.SUCCESS);
        return response;
    }

    //修改商品
    @Override
    @Transactional(readOnly=false, propagation = Propagation.REQUIRED)
    public Response updateGoods(String goodsId, String goodsInfo) {
        Response response = new Response();
        JSONArray jsonArray = JSONArray.fromObject(goodsInfo);//把String转换为json
        List<GoodsInfo> goodsInfoList = JSONArray.toList(jsonArray, new GoodsInfo(), new JsonConfig());
        Goods goods = goodsDao.selectByPrimaryKey(goodsId);
        for (int y = 0; y < goodsInfoList.size(); y++) {
            goods.setWaringValue(goodsInfoList.get(y).getWaringValue());
            goods.setCostPrice(goodsInfoList.get(y).getCostPrice());
            goods.setOriginalPrice(goodsInfoList.get(y).getOriginalPrice());
            goods.setCurrentPrice(goodsInfoList.get(y).getCurrentPrice());
        }
        int i = goodsDao.updateGoods(goods);
        if (i == 1) {
            String[] price =goodsInfoList.get(0).getSellingPrice();
            int size03 = price.length;
            for(int y=0;y<size03;y++){
                String[] newPrice = price[y].split(",");
                GoodsPrice goodsPrice = goodsPriceDao.getGoodsPriceByGoodsIdAndMemberLevelId(goodsId, newPrice[0]);
                if(null!=goodsPrice){
                    goodsPrice.setGoodsPrice(Integer.parseInt(newPrice[1]));
                    goodsPriceDao.updateByPrimaryKeySelective(goodsPrice);
                }else{
                    GoodsPrice goodsPrice1 = new GoodsPrice();
                    goodsPrice1.setGoodsPrice(Integer.parseInt(newPrice[1]));
                    goodsPrice1.setGoodsId(goodsId);
                    goodsPrice1.setMemberLevelId(newPrice[0]);
                    goodsPrice1.setCreateTime(DateUtils.timeFormat(System.currentTimeMillis()));
                    goodsPriceDao.insert(goodsPrice1);
                }
            }
            //更新索引库
            deleteGoodsIndex(goodsId);
            saveGoodsIndex(goodsId);
            response.setCode(RetCode.SUCCESS);
        }else{
            response.setCode(RetCode.REQUEST_ERROR);
        }
        return response;
    }

    @Override
    public Response searchBoutiqueGoods(String shopId, String categoryId, Integer size) {
        List<Map<String, Object>> list = goodsDao.searchBoutiqueGoods(shopId, categoryId, size);
        Response response = new Response();
        response.setCode(RetCode.SUCCESS);
        response.put("list", list);
        return response;
    }

    @Override
    public Response searchPopularBountiqueGoods(String shopId, Integer size) {
        List<Map<String, Object>> list = goodsDao.searchPopularBountiqueGoods(shopId, size);
        Response response = new Response();
        response.setCode(RetCode.SUCCESS);
        response.put("list", list);
        return response;
    }

    @Override
    public Response searchPopularGoodsByShop(String shopId, Integer page, Integer size) {
        List<Map<String, Object>> list = goodsDao.searchPopularGoodsByShop(shopId, (page - 1) * size, size);
        PageResult<Map<String, Object>> pageList = new PageResult<>(list, page, size, 0, null);
        Response response = new Response();
        response.setCode(RetCode.SUCCESS);
        response.put("pageList", pageList);
        return response;
    }

    @Override
    public Response searchBigBrandBountiqueGoods(Integer size) {
        List<Map<String, Object>> list = goodsDao.searchBigBrandBountiqueGoods(size);
        Response response = new Response();
        response.setCode(RetCode.SUCCESS);
        response.put("list", list);
        return response;
    }

    @Override
    public Response searchRelatedGoods(String goodsId, Integer size) {
        List<Map<String, Object>> list = goodsDao.searchRelatedGoods(goodsId, size);
        Response response = new Response();
        response.setCode(RetCode.SUCCESS);
        response.put("list", list);
        return response;
    }

    @Override
    public Response searchRecommendGoods(String categoryId, Integer size) {
        List<Map<String, Object>> list = goodsDao.searchRecommendGoods(categoryId, size);
        Response response = new Response();
        response.setCode(RetCode.SUCCESS);
        response.put("list", list);
        return response;
    }

    @Override
    public Response searchSpecialGoods(int page, int size, String draw) {
        Integer totalNum = goodsDao.countSpecialGoods();
        List<Map<String, Object>> list = goodsDao.searchSpecialGoods(page, size);

        PageResult<Map<String, Object>> pageList = new PageResult<>(list, page, size, totalNum, draw);
        Response response = new Response();
        response.setCode(RetCode.SUCCESS);
        response.put("pageList", pageList);
        return response;
    }

    @Override
    public Response searchNewGoods(Integer size) {
        List<Map<String, Object>> list = goodsDao.searchNewGoods(size);
        Response response = new Response();
        response.setCode(RetCode.SUCCESS);
        response.put("list", list);
        return response;
    }

    //通过shopid  搜索 商品数量
    @Override
    public int countByShop(String shopId) {
        return goodsDao.countByShop(shopId);
    }

    //前端商城展示商品详情
    @Override
    public Response getProductInfoBySpuNumber(String spuNumber, String customerId) {
         Response response = new Response();

        //查出货品的详情和图片
        Map<String, Object> productMap = productDao.getProductImgAndDescBySpuNumber(spuNumber);

        String memberLevelId = "1";
        //获取用户信息
        if(null!=customerId){
            Customer customer = customerDao.getCustomerById(customerId);
            memberLevelId = customer.getMemberLevelId();
        }

        //通过商品编号查询商品的基础信息
        List<Map<String, Object>> goodsMap = goodsDao.getGoodsInfoAndPriceBySpuNumber(spuNumber, memberLevelId);

        //查出此货品的评论总个数
        Integer amount = evaluateDao.getEvaluateAmountBySpuNumber(spuNumber);

        //调取属性和属性选项
        List<Object> list = productPropertyDao.getOptionByProductId(productMap.get("productId").toString(), spuNumber, "true");

        Map<String, Object> map = new HashMap<>();
        map.put("product", productMap);
        map.put("goods", goodsMap);
        map.put("amount", amount);
        map.put("option", list);
        response.setCode(RetCode.SUCCESS);
        response.setData(map);
        return response;
        //查询出此货品的一条5星好评
        //Map<String, Object> evaluateMap = evaluateDao.getOneFiveStartEvaluateBySpuNumber(spuNumber);
        //查出此货品的5星评论总个数
        //Integer amountFive = evaluateDao.getFiveStartEvaluateAmountBySpuNumber(spuNumber);
        //map.put("evaluate", evaluateMap);
        //map.put("amountFive", amountFive);
    }

    @Override
    public Response getGoodsBySkuNumber(String skuNumber, String customerId) {
        Response response = new Response();

        //获取用户信息
        Customer customer = customerDao.getCustomerById(customerId);

        //通过商品编号查询商品的基础信息
        List<Map<String, Object>> goodsMap = goodsDao.getGoodsInfoAndPriceBySkuNumber(skuNumber, customer.getMemberLevelId());

        if(!goodsMap.isEmpty()){
            response.setCode(RetCode.SUCCESS);
            response.setData(goodsMap);
        }else{
            response.setCode(RetCode.NO_DATA);
        }
        return response;
    }



    //保存商品到索引库
    @Override
    public Response saveGoodsIndex(String id) {
        Response response = new Response();
        //取商品信息
        GoodsItem item = getGoodsItemById(id);

        if (item == null) {
            response.setCode(RetCode.NO_DATA);
            return response;
        }

        solrDao.save(item);
        response.setCode(RetCode.SUCCESS);
        return response;
    }

    // 一键添加所有商品到索引库
    @Override
    public Response saveGoodsIndex() {
        Response response = new Response();
        //取商品信息
        List<GoodsItem> items = getGoodsItemByAll();

        if (items == null) {
            response.setCode(RetCode.NO_DATA);
            return response;
        }
        solrDao.save(items);
        response.setCode(RetCode.SUCCESS);
        return response;
    }

    // 一键修改商品名称同步产品名称
    @Override
    public Response updataProductToGoods() {

        Response response = new Response();
        //取商品信息
        List<Product> productList = productMapper.selectAllProduct();
        if (productList == null) {
            response.setCode(RetCode.NO_DATA);
            return response;
        }else{
            for (int j = 0; j <productList.size() ; j++) {
                    List<Map<String, Object>> goodsList  = goodsDao.getGoodsInfoBySkuNumber(productList.get(j).getSpuNumber());
//                    List<Goods> goodsList  = goodsMapper.selectGoodsBySpuNumber22(productList.get(j).getSpuNumber());
                    if(goodsList.size()>0){
                        for (int i = 0; i < goodsList.size(); i++) {
                            Goods goods =goodsDao.selectByPrimaryKey(goodsList.get(i).get("goodsId").toString());
//                            Goods goods =goodsMapper.selectByPrimaryKey22(goodsList.get(i).getGoodsId());
                            goods.setGoodsName(productList.get(j).getProductName()+"("+goods.getGoodsSpec()+")");
                            goodsMapper.updateByPrimaryKeySelective(goods);
                        }
                    }
               }
            response.setCode(RetCode.SUCCESS);
        }
        return response;
    }


    private List<GoodsItem> getGoodsItemByAll() {
        //取商品信息
        List<GoodsItem> items = goodsDao.getGoodsItemByAll();
        return items;
    }


    private GoodsItem getGoodsItemById(String id) {
        //取商品信息
        GoodsItem item = goodsDao.getGoodsItemById(id);
         if (item != null) {
            //取属性信息
            List<Map<String, Object>> props = goodsDao.getGoodsPropsById(id);
            //组合商品属性信息
            setProps(item, props);
        }
        return item;
    }

    //设置属性
    private void setProps(GoodsItem item, List<Map<String, Object>> props) {
        if (props != null || props.size() > 0) {
            for (int i = 0; i < props.size(); i++) {
                Map<String, Object> prop = props.get(i);
                item.putProp(prop.get("property_name") + "", prop.get("option_value") + "");
            }
        }
    }

    //从 solr 索引库删除
    @Override
    public Response deleteGoodsIndex(String id) {
        Response response = new Response();
        try {
            solrDao.delete(id);
            response.setCode(RetCode.SUCCESS);
        } catch (Exception e) {
            response.setCode(RetCode.REQUEST_ERROR);
        }

        return response;
    }

    @Override
    public Response deleteGoodsIndex() {
        Response response = new Response();
        try {
            solrDao.deleteall();
            response.setCode(RetCode.SUCCESS);
        } catch (Exception e) {
            response.setCode(RetCode.REQUEST_ERROR);
        }
        return response;
    }

    @Override
    public Response searchGoodsByKeyWord22(Integer page,
                                           Integer size,
                                           String sort,
                                           String way) {
        Response response = new Response();
        page = (page == null || page == 0) ? 1 : page;
        size = (size == null) ? 10 : size;
        Long start = Long.valueOf((page - 1) * size);

        GoodsItemResult result = null;
        try {
            result = solrDao.query22(start, size, sort, way);
        } catch (Exception e) {
            logger.error("solr query with error {}", e);
            response.setCode(RetCode.NO_DATA);
            return response;
        }
        response.setCode(RetCode.SUCCESS);
        response.put("categoryList", result.getCategoryList());
        return response;
    }

    /**
     * 返回数据库销量排行榜数据
     * @return
     */
    @Override
    public Response searchBySoldOutGoods() {
        Response response = new Response();
        List<SolrTest> solrTest=solrTestMapper.selectAll();
        PageResult<SolrTest> pageList = new PageResult<SolrTest>(solrTest, 0, 5, 3, "draw");
//        response.setData(solrTest);
        response.put("pageList",pageList);
        response.setCode(RetCode.SUCCESS);
        return response;
    }

    /**
     * 定时更新数据库销量排行榜
     */
    @Override
    @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
    public void updateSoldOutGoods() {
        solrTestMapper.deleteAll();
        Long start = 0L;
        SolrTest solrTest1=new SolrTest();
        GoodsItemResult result = null;
        List<String> sysProps = productPropertyDao.getAllProperty();
        result = solrDao.query(null, null, null, null, null, null, null, null, start, 3, null,"soldOutGoods", "DESC", "app", sysProps);
        List<GoodsItem> items = result.getItems();
        for (int i = 0; i <items.size() ; i++) {
            solrTest1.setGoodsId(items.get(i).getId());
            solrTest1.setSpuNumber(items.get(i).getSpuNumber());
            solrTest1.setProductName(items.get(i).getProductName());
            solrTest1.setProductImg(items.get(i).getProductImg());
            solrTest1.setCurrentPrice(items.get(i).getCurrentPrice());
            solrTestMapper.insertSelective(solrTest1);
        }
    }


    @Override
    public Response searchGoodsByKeyWord(String keyword,
                                         Integer isNews,
                                         Integer isBoutique,
                                         Integer isBigBrand,
                                         String categoryId,
                                         String brandName,
                                         Integer minPrice,
                                         Integer maxPrice,
                                         String[] prop,
                                         Integer page,
                                         Integer size,
                                         String shopId,
                                         String sort,
                                         String way,
                                         String clientType,Integer isHomePage) {
        Response response = new Response();
        page = (page == null || page == 0) ? 1 : page;
        size = (size == null) ? 10 : size;
        Long start = Long.valueOf((page - 1) * size);

        // 精品特卖  选第一个 大牌品牌
        if(isBigBrand != null && isBigBrand==1 ){
          List<Brand> brandList = brandMapper.getBrandByBrandType();
          if(brandList.size()>0){
              brandName = brandList.get(0).getBrandName();
              response.put("brandLogo", brandList.get(0).getBrandLogo());
              response.put("brandDescribe", brandList.get(0).getBrandDescribe());
          }
        }

        if (StringUtils.isEmpty(clientType)) {
            clientType = ClientType.DEFAULT.getCode();
        }
        GoodsItemResult result = null;
        GoodsItemResult result22 = null;// 总条数
        try {
            List<String> sysProps = productPropertyDao.getAllProperty();
            result = solrDao.query(keyword, isNews, isBoutique, categoryId, brandName, minPrice, maxPrice, prop,
                    start, size, sort,shopId, way, clientType, sysProps);
          /*  result22 = solrDao.queryV2(keyword, isNews, isBoutique, categoryId, brandName, minPrice, maxPrice, prop,
                    (long) 0, 999999, sort,shopId, way, clientType, sysProps);*/
        } catch (Exception e) {
            logger.error("solr query with error {}", e);
            response.setCode(RetCode.NO_DATA);
            return response;
        }
        PageResult<GoodsItem> pageList = new PageResult<GoodsItem>(result.getItems(), page, size, result.getTotal(), "draw");
        response.setCode(RetCode.SUCCESS);
        response.put("pageList", pageList);
        response.put("brands", result.getBrands());
        response.put("searchProp", result.getSearchProp().getPropMap());

        return response;
    }

    //产品审核
    @Override
    public Response changeIsAudit(String id, Integer status) {
        Response response = new Response();
//        if (status == 1) {                  //上架 时 把商品添加 solr 索引库
//            saveGoodsIndex(id);
//        }
        int i = productDao.changeIsAudit(id, status);
        if (1 == i) {
            response.setCode(RetCode.SUCCESS);
        } else {
            response.setCode(RetCode.REQUEST_ERROR);
        }
        return response;
    }

    /**
     * 保存商品和属性选项关联表
     * @param goodsId
     * @param newDatum
     * @param optionList
     */
    private void addGoodsOption(String goodsId, String newDatum, List<GoodsOption> optionList) {
        GoodsOption goodsOption = new GoodsOption();
        goodsOption.setGoodsId(goodsId);
        goodsOption.setOptionId(newDatum);
        optionList.add(goodsOption);
    }

    /**
     * 保存价格
     * @param price
     * @param goodsId
     * @param goodsPrices
     */
    private void addGoodsPrice(String price, String goodsId, List<GoodsPrice> goodsPrices) {
        String[] newPrice = price.split(",");
        GoodsPrice goodsPrice = new GoodsPrice();
        goodsPrice.setGoodsPrice(Integer.parseInt(newPrice[1]));
        goodsPrice.setCreateTime(DateUtils.timeFormat(System.currentTimeMillis()));
        goodsPrice.setGoodsId(goodsId);
        goodsPrice.setMemberLevelId(newPrice[0]);
        goodsPrices.add(goodsPrice);
    }

    /**
     * 得到编号
     * @return
     */
    /*private Integer serialNumber(String type) {
        if (type.equals("P")) {
            //得到最大产品编号的数据
            Map<String, Object> map = productDao.getMaxSpuNumber();
            if(null!=map && map.size()>0){
                return Integer.parseInt(map.get("spuNumber").toString());
            }else{
                return 100000;
            }
        } else if (type.equals("G")) {
            //得到最大商品编号的数据
            Map<String, Object> map = goodsDao.getMaxSkuNumber();
            if(null!=map && map.size()>0){
                return Integer.parseInt(map.get("skuNumber").toString());
            }else{
                return 100000;
            }
        }
        return null;
    }*/
    private Integer serialNumber(String type, String spuNumber) {
        if("P".equals(type)){
            Map<String, Object> map = productDao.getMaxSpuNumberFlag();
            if(null!=map && map.size()>0){
                return Integer.parseInt(map.get("spuNumberFlag").toString());
            }else{
                return 100000;
            }
        }else{
            Map<String, Object> map = goodsDao.getMaxSkuNumberFlag(spuNumber);
            if(null!=map && map.size()>0){
                return Integer.parseInt(map.get("skuNumberFlag").toString());
            }
            return null;
        }
    }
}
